package com.whz.iplocation.gzip;


import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.file.Files;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;

/**
 * @author whz
 */
@Slf4j
public class ZlibCompression {


    /**
     * Compresses a file with zlib compression.
     */
    public static void compressFile(File raw, File compressed) {
        try (InputStream in = Files.newInputStream(raw.toPath());
             OutputStream out = new DeflaterOutputStream(Files.newOutputStream(compressed.toPath()))) {
            shovelInToOut(in, out);
        } catch (Exception e) {
            log.error("", e);
        }
    }

    /**
     * Decompresses a zlib compressed file.
     */
    public static void decompressFile(File compressed, File raw) {
        try (InputStream in = new InflaterInputStream(Files.newInputStream(compressed.toPath()));
             OutputStream out = Files.newOutputStream(raw.toPath())) {
            shovelInToOut(in, out);
        } catch (Exception e) {
            log.error("", e);
        }
    }

    public static void decompressFile(byte[] compressed, File raw) {
        try (InputStream in = new InflaterInputStream(new ByteArrayInputStream(compressed));
             OutputStream out = Files.newOutputStream(raw.toPath())) {
            shovelInToOut(in, out);
        } catch (Exception e) {
            log.error("", e);
        }
    }

    public static byte[] decompressFile(byte[] compressed) {
        try (InputStream in = new InflaterInputStream(new ByteArrayInputStream(compressed));
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            shovelInToOut(in, out);
            return out.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("", e);
        }
        return null;
    }

    /**
     * Shovels all data from an input stream to an output stream.
     */
    private static void shovelInToOut(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1000];
        int len;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
    }
}